<template>
  <view class="container">
    <!-- 设置面板 -->
    <view v-if="showSettings" class="settings-overlay" @click="toggleSettings">
      <view class="settings-panel" @click.stop>
        <view class="settings-item">
          <text>题目数量：</text>
          <input type="number" v-model.number="tempQuestionCount" min="1" max="10" class="settings-input"/>
        </view>
        <view class="settings-item">
          <text>字体大小：</text>
          <slider :value="fontSize" min="16" max="32" step="2" @change="onFontSizeChange"/>
        </view>
        <button class="primary-btn" @click="applySettings">应用设置</button>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="isChecking" class="loading-overlay">
      <view class="loading-spinner"></view>
      <text>智能批改中...</text>
    </view>

    <!-- 主界面 -->
    <view class="header">
      <text class="title">{{ practiceTitle }}</text>
      <view class="header-controls">
        <button class="icon-button" @click="toggleSettings">
          <image src="/static/settings-icon.png" class="icon"/>
        </button>
        <text class="timer">{{ formattedTime }}</text>
      </view>
    </view>

    <view class="content">
      <scroll-view scroll-y class="question-list">
        <view
            v-for="(q, index) in currentPageQuestions"
            :key="q.expression + index"
            class="question-item"
            :class="{
              'correct-bg': q.isCorrect,
              'incorrect-bg': q.isCorrect === false
            }"
        >
          <text class="question-index">{{ index + 1 }}.</text>
          <text class="question-text" :style="{ fontSize: fontSize + 'px' }">
            {{ q.expression }} =
          </text>
          <input
              type="number"
              v-model.number="q.userAnswer"
              class="answer-input"
              :disabled="q.isCorrect !== null"
              :style="{ fontSize: fontSize + 'px' }"
              @focus="onInputFocus(index)"
              @blur="onInputBlur"
          />
          <view class="feedback-indicator">
            <text v-if="q.isCorrect !== null" class="iconfont" :class="q.isCorrect ? 'correct' : 'incorrect'">
              {{ q.isCorrect ? '✓' : '✗' }}
            </text>
          </view>
        </view>
      </scroll-view>

      <view class="action-bar">
        <button
            class="primary-btn"
            :class="{ 'disabled-btn': isChecking }"
            @click="checkAnswers"
        >
          {{ submitButtonText }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
const PAGE_SIZE = 5;
// 生成有效的题目
const generateValidQuestion = () => {
  const maxSum = 5;
  const a = Math.floor(Math.random() * (maxSum + 1));
  const b = Math.floor(Math.random() * (maxSum - a + 1));
  return {
    expression: `${a} + ${b}`,
    correctAnswer: a + b,
    userAnswer: null,
    isCorrect: null
  };
};

export default {
  data() {
    return {
      questions: [], // 存储题目列表
      questionCount: 10, // 题目总数
      showSettings: false, // 是否显示设置面板
      startTime: Date.now(), // 开始时间
      currentTime: Date.now(), // 当前时间
      isChecking: false, // 是否正在批改
      fontSize: 20, // 字体大小
      tempQuestionCount: 10, // 临时题目数量（用于设置）
      practiceTitle: '5以内加法练习', // 练习标题
      resultPages: [], // 结果分页
      currentPage: 0, // 当前页码
      errorAnalysis: {} // 错误分析
    };
  },
  computed: {
    // 格式化时间显示
    formattedTime() {
      const seconds = Math.floor((this.currentTime - this.startTime) / 1000);
      return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;
    },
    // 提交按钮文本
    submitButtonText() {
      if (this.isChecking) return '批改中...';
      const answeredCount = this.questions.filter(q => q.userAnswer !== null).length;
      return `提交答案 (${answeredCount}/${this.questionCount})`;
    },
    // 当前页面的题目
    currentPageQuestions() {
      const start = this.currentPage * PAGE_SIZE;
      return this.questions.slice(start, start + PAGE_SIZE);
    }
  },
  created() {
    this.loadSettings();
    this.initializeQuestions();
    this.startTimer();
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    // 初始化题目
    initializeQuestions() {
      this.questions = Array.from({ length: this.questionCount }, generateValidQuestion);
      this.startTime = Date.now();
      this.currentPage = 0;
    },
    // 字体大小变化处理
    onFontSizeChange(e) {
      this.fontSize = e.detail.value;
    },
    // 应用设置
    applySettings() {
      this.questionCount = Math.min(20, Math.max(1, this.tempQuestionCount));
      this.initializeQuestions();
      this.toggleSettings();
      this.saveSettings();
    },
    // 保存设置到本地存储
    saveSettings() {
      uni.setStorageSync('mathPracticeSettings', {
        fontSize: this.fontSize,
        questionCount: this.questionCount
      });
    },
    // 从本地存储加载设置
    loadSettings() {
      const settings = uni.getStorageSync('mathPracticeSettings') || {};
      this.fontSize = settings.fontSize || 20;
      this.questionCount = settings.questionCount || 10;
      this.tempQuestionCount = this.questionCount;
    },
    // 输入框聚焦处理
    onInputFocus(index) {
      uni.pageScrollTo({
        scrollTop: (index % PAGE_SIZE) * 100,
        duration: 300
      });
    },
    // 检查答案
    async checkAnswers() {
      if (this.questions.some(q => q.userAnswer === null)) {
        uni.showToast({ title: '请完成所有题目', icon: 'none' });
        return;
      }

      this.isChecking = true;
      await new Promise(resolve => setTimeout(resolve, 500));

      this.questions.forEach(q => {
        q.isCorrect = q.userAnswer === q.correctAnswer;
      });

      this.errorAnalysis = this.groupErrors(
          this.questions.filter(q => !q.isCorrect)
      );
      this.resultPages = this.chunkArray(this.questions, PAGE_SIZE);
      this.saveResultToHistory();
      this.showResultModal();
      this.isChecking = false;
    },
    // 分组错误
    groupErrors(errors) {
      return errors.reduce((acc, cur) => {
        const errorKey = cur.errorValue > 1 ? '进位错误' : '基本错误';
        acc[errorKey] = (acc[errorKey] || 0) + 1;
        return acc;
      }, {});
    },
    // 数组分块
    chunkArray(arr, size) {
      return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
          arr.slice(i * size, i * size + size)
      );
    },
    // 显示结果模态框
    showResultModal() {
      const correctCount = this.questions.filter(q => q.isCorrect).length;
      const accuracy = ((correctCount / this.questionCount) * 100).toFixed(1);

      uni.showModal({
        title: `练习结果（${this.currentPage + 1}/${this.resultPages.length}）`,
        content: this.formatPageContent(),
        confirmText: this.currentPage < this.resultPages.length - 1 ? '下一页' : '重新开始',
        cancelText: '关闭',
        success: (res) => {
          if (res.confirm) {
            if (this.currentPage < this.resultPages.length - 1) {
              this.currentPage++;
              this.showResultModal();
            } else {
              this.initializeQuestions();
            }
          }
        }
      });
    },
    // 格式化页面内容
    formatPageContent() {
      return this.currentPageQuestions
          .map(q => `${q.expression} = ${q.userAnswer}（${q.isCorrect ? '✓' : '✗'}） → 正确答案：${q.correctAnswer}`)
          .join('\n\n');
    },
    // 启动计时器
    startTimer() {
      this.timer = setInterval(() => {
        this.currentTime = Date.now();
      }, 1000);
    },
    // 切换设置面板显示
    toggleSettings() {
      this.showSettings = !this.showSettings;
    },
    // 保存结果到历史记录
    saveResultToHistory() {
      const history = uni.getStorageSync('practiceHistory') || [];
      history.unshift({
        date: new Date().toISOString(),
        accuracy: ((this.questions.filter(q => q.isCorrect).length / this.questionCount) * 100).toFixed(1),
        duration: this.formattedTime,
        errorAnalysis: this.errorAnalysis
      });
      uni.setStorageSync('practiceHistory', history.slice(0, 10));
    }
  }
};
</script>

<style lang="scss">
// 定义页面的主容器样式
.container {
  flex: 1;
  background: #f8f9fa;
  padding-bottom: env(safe-area-inset-bottom);
}

// 设置页面头部样式
.header {
  padding: 24rpx 32rpx;
  background: linear-gradient(135deg, #4A90E2, #6C5CE7);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 10;

  // 设置标题样式
  .title {
    color: white;
    font-size: 36rpx;
    font-weight: 500;
    text-align: center;
    flex: 1;
  }

  // 设置头部控制按钮样式
  .header-controls {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-top: 16rpx;
  }
}

// 设置覆盖在页面上的设置面板样式
.settings-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;

  // 设置实际的设置面板样式
  .settings-panel {
    background: white;
    padding: 32rpx;
    border-radius: 24rpx;
    width: 80%;
    box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.2);

    // 设置单个设置项样式
    .settings-item {
      flex-direction: row;
      align-items: center;
      margin-bottom: 32rpx;
    }
  }
}

// 设置主要内容区域样式
.content {
  flex: 1;
  padding: 24rpx;

  // 设置问题列表样式
  .question-list {
    max-height: 70vh;
    margin-bottom: 24rpx;
  }

  // 设置单个问题项样式
  .question-item {
    flex-direction: row;
    align-items: center;
    padding: 16rpx;
    margin: 16rpx 0;
    background: white;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    // 为正确回答的问题项设置背景颜色和动画效果
    &.correct-bg {
      background: #e8f5e9;
      animation: correctPulse 0.6s ease;
    }

    // 为错误回答的问题项设置背景颜色和动画效果
    &.incorrect-bg {
      background: #ffebee;
      animation: errorShake 0.4s ease;
    }
  }

  // 设置答案输入框样式
  .answer-input {
    width: 140rpx;
    padding: 16rpx;
    border: 2rpx solid #e9ecef;
    border-radius: 8rpx;
    text-align: center;
  }
}

// 定义正确的脉冲动画
@keyframes correctPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.02); }
  100% { transform: scale(1); }
}

// 定义错误的晃动动画
@keyframes errorShake {
  0% { transform: translateX(0); }
  25% { transform: translateX(10px); }
  50% { transform: translateX(-10px); }
  75% { transform: translateX(5px); }
  100% { transform: translateX(0); }
}

// 设置加载覆盖层样式
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;

  // 设置加载动画样式
  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 8rpx solid #f3f3f3;
    border-top: 8rpx solid #4A90E2;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

// 定义旋转动画
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
